<?php
class TasteTimeline {
	static function staticGenerateChangesTimeline($tagsByDate) {
		$overallTagsMaximum = array();
		$changesByDate = array();
		ksort($tagsByDate);
		foreach ($tagsByDate as $date=>$tags) {
			$tagsForThisDate = array();
			foreach($tags as $tag=>$playtime) {
				// Don't include results for the first time the tag is seen
				if (isset($overallTagsMaximum[$tag])) {
					$playtimeDiff = null;
					if ($overallTagsMaximum[$tag] > $playtime) {
						$playtimeDiff = $overallTagsMaximum[$tag] - $playtime;
						$sign = '-';
					} else if ($overallTagsMaximum[$tag] > $playtime) {
						$playtimeDiff = $playtime - $overallTagsMaximum[$tag];
						$sign = '+';
					}
					if ($playtimeDiff !== null) {
						if ($playtimeDiff >= TASTE_BOUNDARY_PERCENT) {
							if (!array_key_exists($date, $changesByDate)) {
								$changesByDate[$date] = array();
							}
							$changesByDate[$date][$tag] = array(
								'old'=>$overallTagsMaximum[$tag],
								'new'=>$playtime,
								'diff'=>$sign.$playtimeDiff,
							);
							$overallTagsMaximum[$tag] = $playtime;
						}
					}
				} else if ($playtime >= NEW_TASTE_BOUNDARY_PERCENT) {
					$overallTagsMaximum[$tag] = $playtime;
					if (!array_key_exists($date, $changesByDate)) {
						$changesByDate[$date] = array();
					}
					$playtimeDiff = $playtime;
					$changesByDate[$date][$tag] = array(
						'old'=>null,
						'new'=>$playtime,
						'diff'=>'+'.$playtimeDiff,
					);
				}
				$tagsForThisDate[$tag] = $playtime;
			}
			foreach($overallTagsMaximum as $tag=>$value) {
				if ($value === 0) {
					continue;
				}
				if (!array_key_exists($tag, $tagsForThisDate)) {
					$changesByDate[$date][$tag] = array(
						'old'=>$overallTagsMaximum[$tag],
						'new'=>0,
						'diff'=>'-'.$overallTagsMaximum[$tag],
					);
					$overallTagsMaximum[$tag] = 0;
				}
			}
		}
		return $changesByDate;
	}

	static function staticGenerateXml($startEndDates, $data)
	{
		$xmlDoc = "<data>\n";
	
		foreach($data as $startTime => $tags)
		{
			foreach($tags as $tag=>$tagData) {
				$xmlDoc .= "<event start=\"". date("r",$startTime) ."\"
				end=\"". date("r", $startEndDates[$startTime]) ."\"
				title=\"Taste Changed\" image=\"/notifications.gif\">\n";
					$xmlDoc .= $tag . " changed by " . number_format($tagData['diff'], 1) . "%";
				$xmlDoc .= "</event>";
			}
		}
		
		$xmlDoc .= "</data>";
		return $xmlDoc;
	}
}
